#include "stdafx.h"
#include "Win32Lib.h"
#include<tchar.h>

#define MAX_PRINT_STRING 1024
//#define MSG_BOX_PRINT
#ifdef _DEBUG
#define MSG_DEBUG_PRINT
#endif

#define MSG_DEBUG_PRINT


#ifdef MSG_FILE_PRINT
TCHAR szFilePrint[MAX_PATH] = TEXT("c:\\out.txt");
BOOL bZeroFile = FALSE;
#endif



void __cdecl TRACEA(LPCSTR lpszFormat, ...)
{
	char szOutput[MAX_PRINT_STRING]; // max printable string length
	va_list v1;
	va_start(v1, lpszFormat);
	//DebugBreak();
	vsprintf_s(szOutput, MAX_PRINT_STRING, lpszFormat, v1);  
#ifdef MSG_DEBUG_PRINT
	OutputDebugStringA(szOutput);
#endif
#ifdef MSG_CONSOLE_PRINT
	printf("%s", szOutput);
#endif
#ifdef MSG_BOX_PRINT
	MessageBoxA(NULL, szOutput, "TRACE Output", MB_OK);
#endif
#ifdef MSG_FILE_PRINT
	{
		char szFilePrint[MAX_PATH] = "c:\\out.txt";
		static HANDLE hFile = NULL;
		DWORD dwNumWritten;
		if (hFile == NULL)
		{
			hFile = CreateFileA(szFilePrint, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 
				bZeroFile ? CREATE_ALWAYS : OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			//if (hFile == INVALID_HANDLE_VALUE)
			//   TRACE("CreateFile output log file %s failed with %s\r\n", szFilePrint, FormatError(GetLastError()));
		}
		if (hFile != INVALID_HANDLE_VALUE)
		{
			OVERLAPPED ol = {0};
			LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &ol);
			SetFilePointer(hFile, 0, 0, FILE_END);
			WriteFilehFile, szOutput, lstrlen(szOutput)*sizeof(char), &dwNumWritten, NULL);
			UnlockFileEx(hFile, 0, 1, 0, &ol);
		}
	}
#endif
}


void __cdecl TRACEW(LPCWSTR lpszFormat, ...)
{
	wchar_t szOutput[MAX_PRINT_STRING]; // max printable string length
	va_list v1;
	va_start(v1, lpszFormat);
	//DebugBreak();
	vswprintf_s(szOutput, MAX_PRINT_STRING, lpszFormat, v1);  
#ifdef MSG_DEBUG_PRINT
	OutputDebugString(szOutput);
#endif
#ifdef MSG_CONSOLE_PRINT
	wprintf(L"%s", szOutput);
#endif
#ifdef MSG_BOX_PRINT
	MessageBoxW(NULL, szOutput, L"TRACE Output", MB_OK);
#endif
#ifdef MSG_FILE_PRINT
	{
		static HANDLE hFile = NULL;
		DWORD dwNumWritten;
		if (hFile == NULL)
		{
			hFile = CreateFileW(szFilePrint, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 
				bZeroFile ? CREATE_ALWAYS : OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			//if (hFile == INVALID_HANDLE_VALUE)
			//   TRACE("CreateFile output log file %s failed with %s\r\n", szFilePrint, FormatError(GetLastError()));
		}
		if (hFile != INVALID_HANDLE_VALUE)
		{
			OVERLAPPED ol = {0};
			LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &ol);
			SetFilePointer(hFile, 0, 0, FILE_END);
			WriteFile(hFile, szOutput, lstrlen(szOutput)*sizeof(TCHAR), &dwNumWritten, NULL);
			UnlockFileEx(hFile, 0, 1, 0, &ol);
		}
	}
#endif
}

